package com.atguigu.eduservice.controller;


import com.atguigu.commonutils.JwtUtils;
import com.atguigu.commonutils.Result;
import com.atguigu.commonutils.vo.UcenterMemberVO;
import com.atguigu.eduservice.client.UcenterClient;
import com.atguigu.eduservice.entity.EduComment;
import com.atguigu.eduservice.service.EduCommentService;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * <p>
 * 评论 前端控制器
 * </p>
 *
 * @author zr
 * @since 2021-11-24
 */
@RestController
@RequestMapping("/edu/service/comment")
@Api(tags = "课程评论管理")
//@CrossOrigin
@Slf4j
public class EduCommentController {
    @Autowired
    private EduCommentService eduCommentService;
    @Autowired
    private UcenterClient ucenterClient;

    /**
     * 分页查询评论
     *
     * @return
     */
    @ApiOperation(value = "分页查询课程评论")
    @GetMapping("pageComment/{current}/{limit}")
    public Result pageComment(@ApiParam(name = "current", value = "当前页码", required = true)
                              @PathVariable long current,
                              @ApiParam(name = "limit", value = "每页记录数", required = true)
                              @PathVariable long limit,
                              @ApiParam(name = "courseId", value = "课程Id", required = false)
                              @RequestParam("courseId") String courseId) {
        //log.info("courseId=======" + courseId);
        Page<EduComment> commentPage = new Page<>(current, limit);
        Map<String, Object> map = eduCommentService.getPageComment(commentPage, courseId);
        return Result.ok(map);
    }

    @ApiOperation(value = "添加课程评论")
    @PostMapping("addComment")
    public Result addComment(@RequestBody EduComment eduComment, HttpServletRequest request
    ) {
        //  根据request对象 获取头信息 返回用户Id
        String memberId = JwtUtils.getMemberIdByJwtToken(request);
        // 判断用户Id是否为空
        if (StringUtils.isEmpty(memberId)) {
            return Result.fail().message("请进行登录");
        }
        // 解决没有存入会员Id的bug
        eduComment.setMemberId(memberId);
        UcenterMemberVO memberInfo = ucenterClient.getMemberInfoById(memberId);
        // 设置会员昵称 和头像
        eduComment.setNickname(memberInfo.getNickname());
        eduComment.setAvatar(memberInfo.getAvatar());
        boolean save = eduCommentService.save(eduComment);
        return save ? Result.ok().message("保存成功") : Result.fail().message("保存失败");
    }
}

